package com.atguigu.flink.chapter07;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/14 9:49
 */
public class Flink08_Window_Reduce {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        
        env.setParallelism(2);
        // 每隔5s计算这5s内的wordCount
        env
            .socketTextStream("hadoop162", 9999)
            .map(new MapFunction<String, WaterSensor>() {
                @Override
                public WaterSensor map(String value) throws Exception {
                    String[] data = value.split(",");
                    return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
                }
            })
            //            .keyBy(ws -> ws.getId())
            .keyBy(WaterSensor::getId)
            .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<WaterSensor>() {
                    @Override
                    public WaterSensor reduce(WaterSensor ws1,
                                              WaterSensor ws2) throws Exception {
                        System.out.println("xxxxx");
                        ws1.setVc(ws1.getVc() + ws2.getVc());
                        return ws1;
                    }
                },
                new WindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    // 当窗口关闭的时候执行这个方法
                    public void apply(String key,
                                      TimeWindow window,
                                      Iterable<WaterSensor> input, // 用于只有一个元素
                                      Collector<String> out) throws Exception {
                        WaterSensor ws = input.iterator().next();
                        out.collect(window + "  " + ws);
                        
                    }
                }
            )
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
